from wordcloud import WordCloud
import matplotlib
matplotlib.use('TkAgg')
import os
"""
评论生成词云
"""
def generate_wordcloud(carid, carname, type=None,show=False):
    import matplotlib.pyplot as plt
    from db_utils import CommentAnalysisDB

    db = CommentAnalysisDB()
    get_all = db.get_by_carid(carid)
    text_cut = []
    for item in get_all:
        if type is None:
            text_cut.extend(item['advantage'].split(','))
            text_cut.extend(item['disadvantage'].split(','))
        elif type == 'a':
            text_cut.extend(item['advantage'].split(','))
        elif type == 'd':
            text_cut.extend(item['disadvantage'].split(','))

    join = ' '.join(text_cut)
    # 确保字体路径正确（Windows 示例）
    wc = WordCloud(
        font_path='simhei.ttf',
        width=1200,  # 更宽的画布容纳更多词
        height=800,
        background_color='white',
        max_words=500,  # 显示最多 500 个词（默认是 200）
        relative_scaling=0.5,  # 保持词频与大小的合理关系
        collocations=False,  # 是否允许重复短语（如“人工智能”出现多次）
        min_font_size=10,  # 减小最小字体，让更多词可见
        max_font_size=100  # 可选：控制最大字体
    ).generate(join)

    plt.figure(figsize=(10, 6))
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    # 设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'WenQuanYi Micro Hei']
    plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号

    # 现在可以显示中文标题了
    type_mapping = {
        'a': '正面评价',
        'd': '负面评价'
    }
    # 默认是综合评价
    title = carname + ('' if type in ['a', 'd'] else '综合评价') + type_mapping.get(type, '')
    plt.title(title, fontsize=16, color='darkred', weight='bold')
    if show:
        plt.show()
    else:
        directory = f'data/{carname}'
        if not os.path.exists(directory):
            os.makedirs(directory)
        plt.savefig(f'{directory}\\{title}.png')


"""
评论生成价格走势图
"""
def generate_trend_chart(carid:str, carname:str = None, show=False,begin_date=None):
    import matplotlib.pyplot as plt
    import pandas as pd

    import pandas as pd
    import matplotlib.pyplot as plt
    from db_utils import UserReviewDB

    # === 第一步：模拟从数据库读取的数据（你实际可用 pd.read_sql() 替代）===
    # 假设这是你从数据库查询的结果

    db = UserReviewDB()
    reviews = db.get_reviews_by_carid(carid)
    # doc = {
    #     'naked_car_price': ['14.08万', '11.78万', '21.53万', '15.20万', '13.60万', '20.00万', '17.50万'],
    #     'review_time': ['2025-07-23', '2025-07-16', '2024-04-24', '2024-05-10', '2024-06-15', '2024-04-30',
    #                     '2025-06-05']
    # }
    reviews = [item for item in reviews
               if item['naked_car_price']
               and item['pickup_date']
               and item['pickup_date'] >= begin_date
               and item['naked_car_price'] != '-']
    data = {
        'naked_car_price': [item['naked_car_price'] for item in reviews],
        'pickup_date': [item['pickup_date'] for item in reviews]
    }
    df = pd.DataFrame(data)

    # === 第二步：数据清洗与转换 ===

    # 1. 转换 price：字符串 → 数值（单位：元）
    def convert_price(price_str):
        if pd.isna(price_str):
            return None
        # 去掉“万”字，转为浮点数，乘以 10000
        if '万' in price_str:
            # return float(price_str.replace('万', '')) * 10000
            return float(price_str.replace('万', '')) * 1
        else:
            return float(price_str)

    df['price'] = df['naked_car_price'].apply(convert_price)

    # 2. 转换时间：字符串 → datetime
    df['pickup_date'] = pd.to_datetime(df['pickup_date'])

    # 3. 提取年月（用于分组）
    df['year_month'] = df['pickup_date'].dt.to_period('M')  # 如 '2024-04'

    # === 第三步：按月统计价格 ===
    monthly_stats = df.groupby('year_month')['price'].agg(
        avg_price='mean',
        max_price='max',
        min_price='min'
    ).round(0).astype(int).reset_index()

    # 将 Period 转为字符串，便于绘图
    monthly_stats['year_month'] = monthly_stats['year_month'].astype(str)

    # === 第四步：绘制折线图 ===

    # 设置中文字体（防止小方框）
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS']
    plt.rcParams['axes.unicode_minus'] = False

    # 创建图形
    plt.figure(figsize=(12, 6))
    plt.plot(monthly_stats['year_month'], monthly_stats['avg_price'], marker='o', label='月平均裸车价')
    plt.plot(monthly_stats['year_month'], monthly_stats['max_price'], marker='^', linestyle='--', label='月最高裸车价')
    plt.plot(monthly_stats['year_month'], monthly_stats['min_price'], marker='s', linestyle=':', label='月最低裸车价')

    # 标题和标签
    plt.title(f'{carname}每月裸车价格趋势（平均/最高/最低）', fontsize=16, color='darkslategray')
    plt.xlabel('月份')
    plt.ylabel('价格（万元）')
    plt.xticks(rotation=45)
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()

    # 显示图表
    title = carname + '每月裸车价格趋势'
    if show:
        plt.show()
    else:
        directory = f'data/{carname}'
        if not os.path.exists(directory):
            os.makedirs(directory)
        plt.savefig(f'{directory}\\{title}.png')


if __name__ == '__main__':
    carid = 305
    carname = '比亚迪秦 DM'
    generate_wordcloud(carid, carname)
    generate_wordcloud(carid, carname, 'a')
    generate_wordcloud(carid, carname, 'd')
    generate_trend_chart(carid=str(carid), carname=carname, begin_date='2021-01')
